#include <iostream>
#include <coroutine>
#include <chrono>
#include <thread>

// 定义Awaiter结构体
struct MyAwaiter {
    int milliseconds;

    bool await_ready() const noexcept { return false; }
    void await_suspend(std::coroutine_handle<> handle) {
        // 使用std::this_thread::sleep_for来模拟异步等待
        std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
        handle.resume(); // 等待时间结束后恢复协程
    }
    void await_resume() {}
};

// 定义协程返回类型
struct MyTask {
    struct promise_type;
    std::coroutine_handle<promise_type> handle;

    MyTask(std::coroutine_handle<promise_type> h) : handle(h) {}
    ~MyTask() {
        if (handle)
            handle.destroy();
    }

    bool resume() {
        if (!handle.done()) {
            handle.resume();
            return true;
        }
        return false;
    }

    struct promise_type {
        // 必需的成员函数
        promise_type() = default;
        
        auto get_return_object() {
            return MyTask{std::coroutine_handle<promise_type>::from_promise(*this)};
        }
        std::suspend_never initial_suspend() { return {}; }
        std::suspend_never final_suspend() noexcept { return {}; }
        void unhandled_exception() { std::terminate(); }
        void return_void() {}

        // 自定义await_transform函数，用于处理整数类型的co_await
        MyAwaiter await_transform(int ms) {
            return MyAwaiter{ms};
        }
    };
};

// 示例协程函数
MyTask asyncWaitExample() {
    std::cout << "Starting async wait for 1000 ms...\n";
    co_await 1000; // 使用await_transform将整数转换为awaiter
    std::cout << "Finished waiting.\n";

    std::cout << "Starting async wait for 500 ms...\n";
    co_await 500;
    std::cout << "Finished waiting again.\n";
}

int main() {
    auto task = asyncWaitExample();
    while (task.resume()); // 循环调用resume直到协程完成
    return 0;
}